package com.alibaba.csp.sentinel.dashboard.rule.nacos.config;

import com.alibaba.csp.sentinel.dashboard.rule.nacos.*;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.Properties;

/**
 * NacosConfiguration
 *
 * @author kancy
 * @date 2020/5/4 10:40
 */
@ConditionalOnProperty(value = "sentinel.datasource.mode", havingValue = "nacos")
@Configuration
public class NacosConfiguration {

    @Bean
    @ConfigurationProperties("sentinel.dashboard.datasource.nacos")
    public NacosProperties nacosProperties(){
        return new NacosProperties();
    }

    /**
     * Nacos Config Service
     * @param nacosProperties
     * @return
     * @throws NacosException
     */
    @Bean
    public ConfigService configService(NacosProperties nacosProperties) throws NacosException {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, nacosProperties.getServerAddr());
        if (StringUtils.hasText(nacosProperties.getNamespace())){
            properties.put(PropertyKeyConst.NAMESPACE, nacosProperties.getNamespace());
        }
        if (StringUtils.hasText(nacosProperties.getUsername())
                && StringUtils.hasText(nacosProperties.getPassword())){
            // 配置用户名
            properties.put(PropertyKeyConst.USERNAME, nacosProperties.getUsername());
            // 配置密码
            properties.put(PropertyKeyConst.PASSWORD, nacosProperties.getPassword());
        }
        return NacosFactory.createConfigService(properties);
    }

    @Bean
    public AuthorityRuleNacosService dynamicAuthorityRuleService(){
        return new AuthorityRuleNacosService();
    }

    @Bean
    public DegradeRuleNacosService dynamicDegradeRuleService(){
        return new DegradeRuleNacosService();
    }

    @Bean
    public FlowRuleNacosService dynamicFlowRuleService(){
        return new FlowRuleNacosService();
    }

    @Bean
    public ParamFlowRuleNacosService dynamicParamFlowRuleService(){
        return new ParamFlowRuleNacosService();
    }

    @Bean
    public SystemRuleNacosService dynamicSystemRuleService(){
        return new SystemRuleNacosService();
    }

    @Bean
    public GatewayFlowRuleNacosService dynamicGatewayFlowRuleService(){
        return new GatewayFlowRuleNacosService();
    }

    @Bean
    public GatewayApiRuleNacosService dynamicGatewayApiRuleService(){
        return new GatewayApiRuleNacosService();
    }
}
